#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <qrencode.h>
#include <opencv2/opencv.hpp>
#include <filesystem>
#include <cstdlib>  // for system()
#include <opencv2/objdetect.hpp>
#include <set>  // 用于记录已解码序号

using namespace std;
using namespace cv;
namespace fs = std::filesystem;

struct Frame {
    uint8_t startDelimiter = 0x7E; // 帧首定界符
    uint8_t destAddress;            // 目的地址
    uint8_t srcAddress;             // 源地址
    uint16_t length;                // 数据长度
    vector<unsigned char> payload;  // 载荷
    uint32_t crc = 0;

    uint32_t crc32(const vector<unsigned char>& data) {
        uint32_t crc = 0xFFFFFFFF; // 初始值
        const uint32_t polynomial = 0xEDB88320; // CRC-32 多项式

        for (unsigned char byte : data) {
            crc ^= byte; // 逐字节 XOR
            for (int i = 0; i < 8; ++i) {
                // 如果最低位为 1，则进行多项式除法
                if (crc & 1) {
                    crc = (crc >> 1) ^ polynomial;
                } else {
                    crc >>= 1;
                }
            }
        }
        return ~crc; // 取反
    }

    vector<unsigned char> toVector() const {
        vector<unsigned char> result;

        result.push_back(startDelimiter);
        result.push_back(destAddress);
        result.push_back(srcAddress);
        result.push_back(static_cast<unsigned char>(length >> 8)); // 高字节
        result.push_back(static_cast<unsigned char>(length & 0xFF)); // 低字节
        result.insert(result.end(), payload.begin(), payload.end());
        result.push_back(static_cast<unsigned char>(crc >> 24));
        result.push_back(static_cast<unsigned char>((crc >> 16) & 0xFF));
        result.push_back(static_cast<unsigned char>((crc >> 8) & 0xFF));
        result.push_back(static_cast<unsigned char>(crc & 0xFF));

        return result;
    }
};